package com.yan.jingdongshop.dao;

import com.yan.jingdongshop.domain.Goods;

import java.io.*;
import java.util.Collection;
import java.util.TreeMap;

/**
 * @author taoge
 * @Date 2024/8/2 18:42
 * @Description
 */
public class Dao {
    public static final TreeMap<String , Goods> goods = new TreeMap<>();
    public static final TreeMap<String , Goods> shopCart = new TreeMap<>();

    static {
        BufferedReader br = null;
        try {
             br = new BufferedReader(new FileReader("D:\\IdeaProject\\javaSE-Plus\\day11_code\\src\\com\\yan\\jingdongshop\\dao\\data.txt"));
            //BufferedWriter bw = new BufferedWriter(new FileWriter("D:\\IdeaProject\\javaSE-Plus\\day11_code\\src\\com\\yan\\jingdongshop\\dao\\data.txt"));
            String temp = null;
            while ((temp = br.readLine()) != null) {
                String[] split = temp.split("-");
                goods.put(split[0] , new Goods(split[0] , split[1] , Double.parseDouble(split[2]), split[3] , Integer.parseInt(split[4]) , Integer.parseInt(split[5])));
            }
            //bw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

   public static void save(Goods good) throws IOException {
       Dao.goods.put(good.getId() , good);
       BufferedWriter bw = new BufferedWriter(new FileWriter("D:\\IdeaProject\\javaSE-Plus\\day11_code\\src\\com\\yan\\jingdongshop\\dao\\data.txt"));
       Collection<Goods> values = goods.values();
       for (Goods value : values) {
           String s = value.getId() + "-" + value.getName() + "-" + value.getPrice() + "-" + value.getColour() + "-" + value.getDimension() + "-" + value.getStoke();
           bw.write(s);
           bw.newLine();
           bw.flush();
       }
   }

   public static void saveBuyCar(Goods good) throws IOException {
       Dao.shopCart.put(good.getId() , good);
       BufferedWriter bw = new BufferedWriter(new FileWriter("D:\\IdeaProject\\javaSE-Plus\\day11_code\\src\\com\\yan\\jingdongshop\\dao\\buyCar.txt"));
       Collection<Goods> values = shopCart.values();
       for (Goods value : values) {
          String s = value.getId() + "-" + value.getName() + "-" + value.getPrice() + "-" + value.getColour() + "-" + value.getDimension() + "-" + value.getStoke();
            bw.write(s);
            bw.newLine();
            bw.flush();
       }
       bw.close();
   }
}
